package com.howie.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.common.utils.StringUtils;
import com.howie.common.to.es.SkuEsModel;
import com.howie.common.utils.R;
import com.howie.gulimall.search.config.GulimallElasticSearchConfig;
import com.howie.gulimall.search.constant.EsConstant;
import com.howie.gulimall.search.feign.FeignProductService;
import com.howie.gulimall.search.service.MallSearchService;
import com.howie.gulimall.search.vo.AttrResponseVo;
import com.howie.gulimall.search.vo.SearchParam;
import com.howie.gulimall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: laizhenghua
 * @date: 2021/2/20 16:48
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;
    @Autowired
    private FeignProductService feignService;
    @Override
    public SearchResult search(SearchParam param) {
        /*
        es查询结果方式：模糊匹配、过滤(按照属性，分类，品牌，价格区间，库存)、排序、分页、高亮，聚合分析等
        如果是嵌入式的属性，查询、聚合、分析都应该使用嵌入式的书写方式
         */
        SearchResult result = null;
        // 1、动态构建出查询需要的DSL查询(准备检索请求)
        SearchRequest searchRequest = buildSearchRequest(param);
        try {
            // 2、执行检索请求
            SearchResponse searchResponse = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            // 3、分析响应数据封装成我们需要的格式
            result = buildSearchResult(searchResponse,param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 构建结果数据
     * @param searchResponse es检索响应的数据
     * @return SearchResult视图对象
     */
    private SearchResult buildSearchResult(SearchResponse searchResponse,SearchParam param) {
        SearchResult result = new SearchResult();
        // 1、返回所有查询到的商品
        SearchHits hits = searchResponse.getHits();
        // 真实的命中数据
        SearchHit[] productHits = hits.getHits();
        List<SkuEsModel> skuEsModelList = new ArrayList<>();
        if(productHits != null && productHits.length > 0){
            for (SearchHit hit: productHits){
                String productAsString = hit.getSourceAsString(); // 返回String类型的商品对象信息
                SkuEsModel skuEsModel = JSON.parseObject(productAsString, SkuEsModel.class);
                // 设置高亮
                if(StringUtils.isNotEmpty(param.getKeyword())){
                    HighlightField skuTitleAsField = hit.getHighlightFields().get("skuTitle");
                    String skuTitle = skuTitleAsField.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitle);
                }
                skuEsModelList.add(skuEsModel);
            }
        }
        result.setProducts(skuEsModelList);
        // 2、当前所有商品涉及到的所有属性信息
        List<SearchResult.AttrVo> attrVoList = new ArrayList<>();
        ParsedNested attrAgg = searchResponse.getAggregations().get("attr_agg"); // 嵌入式聚合信息
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 2.1、设置属性的id
            attrVo.setAttrId(bucket.getKeyAsNumber().longValue());
            // 2.2、设置属性的name
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            attrVo.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
            // 2.3、设置属性名字包含的值
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> values = new ArrayList<>();
            for (Terms.Bucket item : attrValueAgg.getBuckets()) {
                String keyAsString = item.getKeyAsString();
                values.add(keyAsString);
            }
            attrVo.setAttrValue(values);

            attrVoList.add(attrVo);
        }
        result.setAttrVos(attrVoList);
        // 3、当前所有商品涉及到的所有品牌信息
        List<SearchResult.BrandVo> brandVoList = new ArrayList<>();
        ParsedLongTerms brandAgg = searchResponse.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 3.1、设置品牌id
            brandVo.setBrandId(Long.parseLong(bucket.getKeyAsString()));
            // 3.2、设置品牌img
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            // 3.3、设置品牌name
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);
            brandVoList.add(brandVo);
        }
        result.setBrandVos(brandVoList);
        // 4、当前所有商品涉及到的所有分类信息
        ParsedLongTerms catalogAgg = searchResponse.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> catalogBuckets = catalogAgg.getBuckets();
        List<SearchResult.CatalogVo> catalogVoList = new ArrayList<>();
        if(catalogBuckets != null && catalogBuckets.size() > 0){
            for (Terms.Bucket bucket : catalogBuckets) {
                SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
                String key = bucket.getKeyAsString();
                // 4.1、设置分类id(catalogId)
                catalogVo.setCatalogId(Long.parseLong(key));
                // 4.2、设置分类名字(catalogName)
                ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
                catalogVo.setCatalogName(catalogNameAgg.getBuckets().get(0).getKeyAsString());
                catalogVoList.add(catalogVo);
            }
        }
        result.setCatalogVos(catalogVoList);
        // TODO 以上数据从聚合信息中获取，除了商品信息
        // 5、分页信息
        // 5.1、分页信息-页码
        result.setPageNumber(param.getPageNumber());
        // 5.2、分页信息-总记录数
        Long total = hits.getTotalHits().value;
        result.setTotal(total);
        // 5.3、分页信息-总页码-计算得到(总记录数/size+余数)
        int temp = total.intValue()/EsConstant.PRODUCT_PAGE_SIZE;
        Integer totalPages = total.intValue() % EsConstant.PRODUCT_PAGE_SIZE == 0 ? temp : temp + total.intValue() % EsConstant.PRODUCT_PAGE_SIZE;
        result.setTotalPages(totalPages);
        // 5.4、导航页码
        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1;i < totalPages;i++){
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        // 6、构建面包屑导航数据
        if(param.getAttrs() != null && param.getAttrs().size() > 0){
            List<SearchResult.navVo> navVoList = param.getAttrs().stream().map(attr -> {
                SearchResult.navVo navVo = new SearchResult.navVo();
                String[] split = attr.split("_");
                navVo.setNavValue(split[1]);
                Long attrId = Long.parseLong(split[0]);
                R r = feignService.attrInfo(attrId);
                if(r.getCode() == 0){
                    // 远程调用成功
                    AttrResponseVo attrResponseVo = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(attrResponseVo.getAttrName());
                }else{
                    navVo.setNavName(split[0]);
                }
                // 取消了这个面包屑以后，我们要跳转到哪个地方，将请求地址的URL里面的当前置空，拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    // 注意前端传过来的请求参数是编码以后的，我们在处理业务时也要进行编码
                    encode = URLEncoder.encode(attr,"UTF-8");
                    encode = encode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = param.getQueryString().replace("&attrs=" + attr, "");
                navVo.setLink("http://localhost:12000/list.html?" + replace);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVoList);
        }
        return result;
    }

    /**
     * 构造检索请求(DSL语句)
     */
    private SearchRequest buildSearchRequest(SearchParam param){
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); // 通过此类构建DSL语句
        /*
        模糊匹配、过滤(按照属性，分类，品牌，价格区间，库存)
         */
        // 1、构建复合查询 bool
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();
        // 1.1、must-模糊匹配(必须达到所列举条件)
        if(StringUtils.isNotEmpty(param.getKeyword())){
            boolQuery.must(new MatchQueryBuilder("skuTitle",param.getKeyword()));
        }
        // 1.2、filter-过滤，按照三级分类
        if(param.getCatalog3Id() != null){
            boolQuery.filter(new TermQueryBuilder("catalogId",param.getCatalog3Id()));
        }
        // 1.2、filter-过滤，按照多个品牌
        if(param.getBrandId() != null && param.getBrandId().size() > 0){
            boolQuery.filter(new TermsQueryBuilder("brandId",param.getBrandId()));
        }
        // 1.2、filter-过滤，是否有库存(0或1。0->无库存，1->有库存)
        boolQuery.filter(new TermQueryBuilder("hasStock",param.getHasStock() == 1));

        // 1.2、filter-过滤，按照价格区间
        if(StringUtils.isNotEmpty(param.getSkuPrice())){
            /*
            skuPrice=1_500/_500/1000_
            {
                "range": {
                    "skuPrice": {
                        "gte": 1000,
                        "lte": 7000
                    }
                }
            }
            */
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] split = param.getSkuPrice().split("_");
            if(split.length == 2 && !param.getSkuPrice().startsWith("_")){
                // 1_500 -> [1,500]
                rangeQueryBuilder.gte(split[0]).lte(split[1]);
            }else {
                // _500 -> (-&,500]
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQueryBuilder.lte(split[1]);
                } else {
                    // 500_ -> [500,+&)
                    rangeQueryBuilder.gte(split[0]);
                }
            }
            boolQuery.filter(rangeQueryBuilder);
        }
        // 1.2、filter-过滤，按照所有指定属性
        if(param.getAttrs() != null && param.getAttrs().size() > 0){
            // attrs=1_5寸:8寸&attrs=2_16G:8G
            for(String attrStr : param.getAttrs()){
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                // attrsStr = 1_5寸:8寸
                String[] split = attrStr.split("_"); // ["1","5寸:8寸"]
                String attrId = split[0]; // 检索属性id
                String[] attrValues = split[1].split(":"); // 检索属性值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));

                // 嵌入式的查询条件，关键点：检索属性是一个list，每一个属性都必须生成一个过滤条件，而不是多条属性整合为一个过滤条件
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs",nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        sourceBuilder.query(boolQuery);
        /*
        排序、分页、高亮
         */
        // 2.1、sort-排序
        if(StringUtils.isNotEmpty(param.getSort())){
            // sort=saleCount_asc
            String[] split = param.getSort().split("_");
            sourceBuilder.sort(split[0],SortOrder.DESC.toString().equals(split[1]) ? SortOrder.DESC : SortOrder.ASC);
        }
        // 2.2、分页
        // pageNUmber=1 from:0 size:5 -> [0,1,2,3,4]
        // pageNUmber=2 from:5 size:5 -> [5,6,7,8,9]
        sourceBuilder.from(EsConstant.PRODUCT_PAGE_SIZE * (param.getPageNumber() - 1));
        sourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);

        // 2.3、高亮
        if (StringUtils.isNotEmpty(param.getKeyword())){
            sourceBuilder.highlighter(new HighlightBuilder()
                    .field("skuTitle")
                    .preTags("<b style='color:red'>")
                    .postTags("</b>"));
        }
        /*
        聚合分析
         */
        // 1、品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        // 品牌聚合-子聚合
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(10));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(10));
        sourceBuilder.aggregation(brandAgg);
        // 2、分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(10);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(10));
        sourceBuilder.aggregation(catalogAgg);
        // 3、属性聚合
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs"); // 嵌入式聚合书写方式
        // 聚合分析当前所有的attrId
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);
        nested.subAggregation(attrIdAgg);
        // 聚合分析出当前attrId对应的attrName
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(10));
        // 聚合分析出当前attrId对应的所有可能的属性值attrValue
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(10));

        sourceBuilder.aggregation(nested);

        String dsl = sourceBuilder.toString();
        System.out.println("dsl: " + dsl);

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);
    }
}
/*
@Service("brandService")相当于：
<bean id="brandService" class="com.howie.gulimall.product.service.impl.BrandServiceImpl">
    ...
</bean>
 */
